/**********************************************
** @Author: phy
** @Date:   2017-12-12 14:17:37
** @Last Modified by:   phy
***********************************************/
package controllers

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"

	"WebAdminSys/libs"
	"WebAdminSys/models"
	"github.com/dchest/captcha"
)

type LoginController struct {
	BaseController
}

//登录 TODO:XSRF过滤
func (self *LoginController) LoginIn() {
	//if self.userId > 0 {
	//	self.redirect(beego.URLFor("HomeController.Index"))
	//}
	
	if false {
		flash := beego.NewFlash()
		errorMsg := ""
		flash.Error(errorMsg)
		flash.Store(&self.Controller)
		self.redirect(beego.URLFor("LoginController.LoginIn"))
		self.TplName = "login/login.html"
	}

	beego.ReadFromRequest(&self.Controller)
	if self.isPost() {

		username := strings.TrimSpace(self.GetString("username"))
		password := strings.TrimSpace(self.GetString("password"))
		captchaId:= strings.TrimSpace(self.GetString("captchaId"));
		captchaValue := strings.TrimSpace(self.GetString("captcha"));

		if username != "" && password != "" {
			user, err := models.ManageAdminGetByName(username)
			fmt.Println(user)
			flash := beego.NewFlash()
			errorMsg := ""
			
			if(false&&!captcha.VerifyString(captchaId, captchaValue)) { 
				errorMsg = "验证码错误"
			}else if err != nil || user.Password != libs.GetEnCodeByMd5(password+user.Salt) {
				errorMsg = "帐号或密码错误"
			} else if user.Status == -1 {
				errorMsg = "该帐号已禁用"
			} else{
				user.LastIp = self.getClientIp()
				user.LastLogin = time.Now().Unix()
				user.Update()
				
				self.AddOperationLog("登陆系统",0)
				authkey := libs.GetEnCodeByMd5(self.getClientIp() + "|" + user.Password + user.Salt)
				self.Ctx.SetCookie(libs.GetEnCodeByMd5("auth"), strconv.Itoa(user.Id)+"|"+authkey, 0)
				
				self.redirect(beego.URLFor("HomeController.Index"))
				
			}
			flash.Error(errorMsg)
			flash.Store(&self.Controller)
			self.redirect(beego.URLFor("LoginController.LoginIn"))
			
		}
	}
	self.TplName = "login/login.html"
}
func CheckUserCookie(ctx *context.Context,lostIp string ) bool {

	arr := strings.Split(ctx.GetCookie(libs.GetEnCodeByMd5("auth")), "|")
	if len(arr) == 2 {
		idstr, password := arr[0], arr[1]
		userId, _ := strconv.Atoi(idstr)
		if userId > 0 {
			user, err := models.ManageAdminGetById(userId)
			if err != nil || password == libs.GetEnCodeByMd5(lostIp+"|"+user.Password+user.Salt) {
				return false
			}
			return true
		}
	}
	return false
	
}
//登出
func (self *LoginController) LoginOut() {
	self.Ctx.SetCookie(libs.GetEnCodeByMd5("auth"), "",-1)
	self.redirect(beego.URLFor("LoginController.LoginIn"))
}

func (self *LoginController) NoAuth() {
	self.Ctx.WriteString("没有权限")
}
